package sys.service.impl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import org.springframework.util.CollectionUtils;
import sys.constants.UserConstant;
import sys.core.ResponseResult;
import sys.dao.TbUserDao;
import sys.entity.User;
import sys.service.TbUserService;
import sys.entity.PageData;
import sys.utils.ExcelUtil;
import sys.utils.MD5Utils;
import sys.utils.PageUtil;

import java.util.*;

import sys.entity.TbUserEntity;
import sys.utils.SessionUtil;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TbUserServiceImpl implements TbUserService {


    private final TbUserDao dao;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public TbUserServiceImpl(TbUserDao dao) {
        this.dao = dao;
    }

    @Override
    public void add(TbUserEntity entity) {
        Random random = new Random();
        int salt = random.nextInt(100000);
        //password加密
        String password = MD5Utils.encode(entity.getPassword() + salt);
        //保存盐值 salt
        entity.setSalt(salt);
        entity.setPassword(password);
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        dao.insert(entity);


    }

    @Override
    public void delete(TbUserEntity entity) {
        dao.deleteById(entity.getId());
    }

    @Override
    public void update(TbUserEntity entity) {
        dao.updateById(entity);
    }

    @Override
    public PageData<TbUserEntity> select(TbUserEntity entity) {

        LambdaQueryWrapper<TbUserEntity> wrapper = new LambdaQueryWrapper<>();
        if (entity.getUsername() != null && !entity.getUsername().equals("")) {
            wrapper.eq(TbUserEntity::getUsername, entity.getUsername());
        }
        if (entity.getPassword() != null && !entity.getPassword().equals("")) {
            wrapper.eq(TbUserEntity::getPassword, entity.getPassword());
        }
        //字段名，前台给的值
        if (entity.getUserLevel() != null && !entity.getUserLevel().equals("")) {
            wrapper.like(TbUserEntity::getUserLevel, entity.getUserLevel());
        }
        if (entity.getSex() != null) {
            wrapper.eq(TbUserEntity::getSex, entity.getSex());
        }

        // List<TbUserEntity> tbUserEntities = dao.selectList(wrapper);
        //查询第几页，每页几条
        IPage<TbUserEntity> page = new Page<>(entity.getCurrentPage() == null ? 1 : entity.getCurrentPage(), entity.getPageSize() == null ? 10 : entity.getPageSize());
        //分页查询拿到结果
        IPage<TbUserEntity> tbUserEntityIPage = dao.selectPage(page, wrapper);
        //获取记录
        List<TbUserEntity> tbUserEntities = tbUserEntityIPage.getRecords();
        PageData<TbUserEntity> pageData = new PageData<>();
        //设置获取的数据
        pageData.setResult(tbUserEntities);
        pageData.setTotalPage((int) tbUserEntityIPage.getPages());
        pageData.setCurrentPage((int) tbUserEntityIPage.getCurrent());
        pageData.setCount((int) tbUserEntityIPage.getTotal());

        return pageData;
    }

    @Override
    public List<TbUserEntity> selectAll(TbUserEntity entity) {
        return dao.selectAll(entity);
    }


    @Override
    public void exportExcel(TbUserEntity entity, HttpServletResponse response) {

        // 获取头部信息（可以设置为动态）
        String[] headList = new String[]{"主键", "用户名", "密码", "创建时间", "更新时间", "1.青铜2.白银3.黄金", "1男0女", "角色id", "email", "phone", "hobby"};

        String[] headEngList = new String[]{"id", "username", "password", "createTime", "updateTime", "userLevel", "sex", "roleId", "email", "phone", "hobby"};

        String[] describeList = new String[]{"", "", "", "", "", "", "", "", "", "", ""};

        //设置头部以及描述信息
        Map<String, String> headAndDescribeMap = new LinkedHashMap<>();
        for (int i = 0; i < headEngList.length; i++) {
            headAndDescribeMap.put(headEngList[i], describeList[i]);
        }

        // ExcelUtil.exportExcel(entity, response, dao, headList, headAndDescribeMap, "");
    }

    @Override
    public ResponseResult login(User user, HttpServletRequest request) {

        //先查redis,有没有此用户
        if (user.getId() != null && !user.getId().equals("")) {
            String key = UserConstant.LOGIN_USER + user.getId();
            //login_user
            Boolean flag = stringRedisTemplate.hasKey(key);
            if (flag) {
                String value = stringRedisTemplate.opsForValue().get(key);
                //json串转对象
                TbUserEntity userEntity = JSON.parseObject(value, TbUserEntity.class);
                String pass = MD5Utils.encode(user.getPassword() + userEntity.getSalt());
                if (pass.equals(userEntity.getPassword())) {
                    //用户信息存到session
                    user.setPhone(userEntity.getPhone());
                    SessionUtil.onLogin(user, request);
                    return ResponseResult.success(user);

                } else {
                    return ResponseResult.success("用户名或密码错误");
                }

            }
        }


        //判断用户名是否存在
      /*  TbUserEntity tbUserEntity = new TbUserEntity();
        tbUserEntity.setUsername(user.getUserName());*/
        //根据用户名查询用户信息
        QueryWrapper<TbUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUserName());
        List<TbUserEntity> userList = dao.selectList(queryWrapper);
        // List<TbUserEntity> userList = dao.select(tbUserEntity);
        if (CollectionUtils.isEmpty(userList) || userList.size() > 1) {
            return ResponseResult.failed("用户名错误！");
        }
        //获取用户信息
        TbUserEntity tbUserEntity1 = userList.get(0);
        //前端传的密码+后台查询的盐值 进行md5加密
        String password = MD5Utils.encode(user.getPassword() + tbUserEntity1.getSalt());
        log.info("密码：{}",password);
        user.setPassword(password);
        User returnUser = dao.login(user);
        log.info("盐值：{}",tbUserEntity1.getSalt());
        if (returnUser == null) {
            return ResponseResult.failed("用户名或密码错误！");
        }
        //用户信息保存到redis中 key前缀
        String userJsonString = JSON.toJSONString(tbUserEntity1);
        //对象转成json串
        stringRedisTemplate.opsForValue().set(UserConstant.LOGIN_USER + tbUserEntity1.getId(), userJsonString, UserConstant.TIMEOUT, TimeUnit.MINUTES);

        //用户信息存到session
        //保存手机号到user
        returnUser.setPhone(tbUserEntity1.getPhone());
        SessionUtil.onLogin(returnUser, request);
        returnUser.setPassword("");
        return ResponseResult.success(returnUser);
    }


}
